package com.jintian.smart.kernel.autoconfigure.extend.work;

import com.jintian.smart.kernel.autoconfigure.extend.resposity.WorkerIdAssigner;
import com.jintian.smart.kernel.autoconfigure.extend.resposity.WorkerNodeEntity;
import com.jintian.smart.kernel.autoconfigure.extend.resposity.WorkerNodeResposity;
import com.jintian.smart.kernel.autoconfigure.extend.resposity.WorkerNodeType;
import com.jintian.smart.kernel.autoconfigure.extend.util.DockerUtil;
import com.jintian.smart.kernel.autoconfigure.extend.util.NetUtil;
import com.jintian.smart.kernel.autoconfigure.extend.util.RandomUtil;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class DisposableWorkerIdAssigner implements WorkerIdAssigner {
    private static final Logger LOGGER = LoggerFactory.getLogger(DisposableWorkerIdAssigner.class);

    @Resource
    private WorkerNodeResposity workerNodeResposity;

    @Override
    public long assignWorkerId() {
        // build worker node entity
        WorkerNodeEntity workerNodeEntity = buildWorkerNode();

        // add worker node for new (ignore the same IP + PORT)
        workerNodeResposity.addWorkerNode(workerNodeEntity);
        LOGGER.info("Add worker node:" + workerNodeEntity);

        return workerNodeEntity.getId();
    }

    private WorkerNodeEntity buildWorkerNode() {
        WorkerNodeEntity workerNodeEntity = new WorkerNodeEntity();
        if (DockerUtil.isDocker()) {
            workerNodeEntity.setType(WorkerNodeType.CONTAINER.value());
            workerNodeEntity.setHostName(DockerUtil.getDockerHost());
            workerNodeEntity.setPort(DockerUtil.getDockerPort());
        } else {
            workerNodeEntity.setType(WorkerNodeType.ACTUAL.value());
            workerNodeEntity.setHostName(NetUtil.getLocalAddress());
            workerNodeEntity.setPort(System.currentTimeMillis() + "-" + RandomUtil.randomInt(0, 100000));
        }
        return workerNodeEntity;
    }
}
